package thread;

/**
 * @author lwmzzz
 * @version 1.0
 * @date 2021/1/24 23:12
 * @description 多线程卖票
 */
public class ThreadDemo {
    public static void main(String[] args) {
//        Window window1 = new Window();
//        Window window2 = new Window();
//        Window window3 = new Window();
//
//        window1.setName("窗口1");
//        window2.setName("窗口2");
//        window3.setName("窗口3");
//
//        window1.start();
//        window2.start();
//        window3.start();


        WindowsThread windowsThread1 = new WindowsThread();
        WindowsThread windowsThread2 = new WindowsThread();
        WindowsThread windowsThread3 = new WindowsThread();

        windowsThread1.setName("窗口1");
        windowsThread2.setName("窗口2");
        windowsThread3.setName("窗口3");

        windowsThread1.start();
        windowsThread2.start();
        windowsThread3.start();
    }

}

class Window extends Thread {
    //100张票
//    private int ticket = 100;
    /**
     * 100张票--->非static属性，New 一个对象，就会分配一个ticket ，改成static 共享
     * 但是无法解决线程安全问题---> ticket还未--，下一个线程就开始处理数据-->线程不安全
     * todo 解决线程安全问题
     */
    private static int ticket = 100;

    @Override
    public void run() {
        while (ticket > 0) {
            System.out.println(getName() + ": 卖票，票号为： " + ticket);
            ticket--;
        }
    }
}

class WindowsThread extends Thread {
    private static int ticket = 100;

    @Override
    public void run() {
        while (true) {
            if (ticket > 0) {
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(getName() + ": 卖票，票号为： " + ticket);
                ticket--;
            } else {
                break;
            }

        }
    }
}